package com.xie.web;

import com.github.pagehelper.PageInfo;
import com.xie.pojo.BaiduWap;
import com.xie.pojo.BaiduWapTj;
import com.xie.pojo.User;
import com.xie.service.BaiduWapService;
import com.xie.service.UserService;
import net.sf.jsqlparser.expression.CastExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
public class Index {

    @Autowired
    BaiduWapService baiduWapService;
    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender mailSender;



    @RequestMapping("/")
    public String index(Model model,
                        @RequestParam(name = "pages",defaultValue = "1") Integer pages,
                        @RequestParam(name = "pagesSize",defaultValue = "5") Integer pageSize,
                        @RequestParam(name = "key",defaultValue = "") String key,
                        @RequestParam(name = "type",defaultValue = "1") Integer type){
        PageInfo<BaiduWap> pageInfo = baiduWapService.findAll(pages, pageSize, key,type);
        List<BaiduWap> byDesc = baiduWapService.findByDesc();
        model.addAttribute("waps",pageInfo.getList());
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("phb",byDesc);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            UserDetails userDetails = (UserDetails)auth.getPrincipal();

            Integer money = userService.findUserByName(userDetails.getUsername()).getMoney();
            model.addAttribute("money",money);
        }
        return "index";
    }

    @PostMapping("findAllByAjax")
    public String selectAll(Model model,
                            @RequestParam(name = "pages",defaultValue = "1") Integer pages,
                            @RequestParam(name = "pageSize",defaultValue = "5") Integer pageSize,
                            @RequestParam(name = "key",defaultValue = "") String key,
                            @RequestParam(name = "type",defaultValue = "1") Integer type){
        PageInfo<BaiduWap> pageInfo = baiduWapService.findAll(pages, pageSize, key,type);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("waps",pageInfo.getList());
        return "index::table_refresh";

    }

    @RequestMapping("updateMoney")
    public String updateMoney(Model model){
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userByName = userService.findUserByName(user.getUsername());
        model.addAttribute("money",userByName.getMoney());
        return "index::money_data";
    }

    @GetMapping("/add")
    @ResponseBody
    public void add(Integer id,HttpServletResponse rs){
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User userByName = userService.findUserByName(user.getUsername());
        boolean isHave=userService.checkWap(id,userByName.getId());
        if (isHave){
            rs.setStatus(200);
        }else {
            if (userByName.getMoney()-100 >=0){
                userByName.setMoney(userByName.getMoney()-100);
                userService.update(userByName);
                baiduWapService.updateCount(id);
                userService.addUserZy(userByName.getId(),id);
                rs.setStatus(200);
            }else{
                rs.setStatus(500);
            }
        }

    }



    @RequestMapping("/sendEmail")
    @ResponseBody
    public Map<String,String> sendEmail(String email){
        StringBuffer code=new StringBuffer();
        Random random=new Random();
        for (int i = 0; i < 4; i++) {
            code.append(random.nextInt(10));
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("981800006@qq.com");
        message.setTo(email);
        message.setSubject("哎呀,你终于来了");
        message.setText(code.toString());
        mailSender.send(message);
        Map<String,String> map=new HashMap<>();
        map.put("code",code.toString());
        return map;
    }
    @RequestMapping("/register")
    @ResponseBody
    public void register(@RequestParam String name,@RequestParam String password,@RequestParam String email,HttpServletResponse rs){
        User userByName = userService.findUserByName(name);
        if (null!=userByName){
            rs.setStatus(500);
        }else {
            User user=new User();
            user.setName(name);
            user.setPassword(new BCryptPasswordEncoder().encode(password));
            user.setEmail(email);
            user.setMoney(300);
            userService.addUser(user);
            rs.setStatus(200);
        }
    }

    @RequestMapping("/toPass")
    @PreAuthorize("hasRole('ADMIN')")
    public String toPass(Model model){
        List<BaiduWapTj> tjAll = baiduWapService.findTjAll();
        model.addAttribute("zytjs",tjAll);
        return "pass";
    }

    @RequestMapping("checkUser")
    @ResponseBody
    public void checkUser(HttpServletResponse rs){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if ((auth instanceof AnonymousAuthenticationToken)) {
            rs.setStatus(403);
        }else {
            rs.setStatus(200);
        }
    }

}
